#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xmlunicode.h>
#include <libxml/xmlreader.h>
#include "Service.h"
#include <fcntl.h>

/// <summary>
/// Locals
/// </summary>
xmlTextReaderPtr reader;
#define XML_IS_BEGIN(reader) (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT)
#define XML_IS_NODE(reader, name) (strcmp(xmlTextReaderConstName(reader), name) == 0)
#define XML_IS_SERVICE(reader) (strcmp(xmlTextReaderConstName(reader), "Service") == 0)
#define XML_IS_NAME(reader) (strcmp(xmlTextReaderConstName(reader), "Name") == 0)
#define XML_IS_FILE(reader) (strcmp(xmlTextReaderConstName(reader), "File") == 0)

/// <summary>
/// TODO
/// </summary>
int ReaderOpen(const char *filename)
{
	ReaderClose();
	if (!(reader = xmlReaderForFile(filename, NULL, XML_PARSE_NONET)))
		return -1;
	return 0;
}

/// <summary>
/// Moves the position of
/// the current instance to the
/// next node in the reader,
/// exposing its properties.
/// </summary>
int ReaderNext(void)
{
	if (xmlTextReaderRead(reader) < 0)
		return -1;
	return 0;
}

/// <summary>
/// TODO
/// </summary>
int ReaderNextNode(const char *name)
{
	while (xmlTextReaderRead(reader) > 0)
		if (XML_IS_BEGIN(reader) && XML_IS_NODE(reader, name))
			return 1;
	return 0;
}

/// <summary>
/// TODO
/// </summary>
int ReaderFillService(ServicePtr srv)
{
	if (srv == NULL)
		return 1;

	/* Name */
	ReaderNextNode("Name");
	printf("%s\n", xmlTextReaderConstName(reader));

	ReaderNextNode("File");
	printf("%s\n", xmlTextReaderConstName(reader));

	//if (XML_IS_NAME(reader))
	//	printf("%s\n", xmlTextReaderConstValue(reader));
		//strcpy(srv->Name, xmlTextReaderConstValue(reader));

	return 1;
}

/// <summary>
/// TODO
/// </summary>
int ReaderNextService(ServicePtr service)
{
	if (service == NULL)
		return 0;
	while (xmlTextReaderRead(reader) > 0)
		if (XML_IS_BEGIN(reader) && XML_IS_SERVICE(reader))
			return ReaderFillService(service);
	return 0;
}

/// <summary>
/// This method releases any
/// resources allocated by the current
/// instance changes the state to Closed
/// and close any underlying input.
/// </summary>
int ReaderClose(void)
{
	if (xmlTextReaderClose(reader) < 0)
		return -1;
	xmlCleanupParser();
	reader = NULL;
	return 0;
}